package com.cn.transfer.jobhandler.duplicates;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.*;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;


/**
 * @author: weidian
 * @date: 2024/1/12 17:04
 * @Description: 公共方法
 */
@Component
public class Connme {
    private static final Map<String, Class<?>> ENTITY_CLASS_MAP = new HashMap<>();
    static {
        ENTITY_CLASS_MAP.put("VvSaSaleDelivery", VvSaSaleDelivery.class);
        ENTITY_CLASS_MAP.put("VvPuPurchaseRequisition", VvPuPurchaseRequisition.class);
        ENTITY_CLASS_MAP.put("VvPuPurchaseArrival", VvPuPurchaseArrival.class);
        ENTITY_CLASS_MAP.put("SalesRecord", SalesRecord.class);
        ENTITY_CLASS_MAP.put("PurchaseRecord", PurchaseRecord.class);
        // Add more mappings as needed
    }

    @XxlJob("ConnmeDan")
    public void connmeDan() {
        String param = XxlJobHelper.getJobParam();
        String[] methodParams = param.split(",");
        String appId=methodParams[0];
        String entryId=methodParams[1];
        String entityName=methodParams[2];
        String fieldName= methodParams[3];
        List<Object> entityList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);
        boolean flag = true;
        String zh = "";

        do {
            if (!zh.equals("")) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonData = JSONUtil.toJsonStr(parameter);

            JSONObject jdyData = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonData);
            String data = jdyData.getStr("data");

            JSONArray objects = JSONUtil.parseArray(data);
            Class<?> entityClass = ENTITY_CLASS_MAP.get(entityName.trim());
            List<?> entityLists = JSONUtil.toList(objects, entityClass);
            entityList.addAll(entityLists);
            if (entityLists.size() == 100) {
                // 使用反射获取 _id 属性的值
                Object lastEntity = entityLists.get(entityLists.size() - 1);
                try {
                    Field idField = entityClass.getDeclaredField("_id");
                    idField.setAccessible(true);
                    Object idValue = idField.get(lastEntity);
                    zh = (idValue != null) ? idValue.toString() : null;
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            } else {
                flag = false;
            }
        } while (flag);

        Set<String> uniqueSet = new HashSet<>();
        List<String> duplicates = new ArrayList<>();

        for (Object entity : entityList) {
            String fieldValue = ReflectUtil.getFieldValue(entity, fieldName.trim()).toString();
            if (!uniqueSet.add(fieldValue)) {
                duplicates.add(ReflectUtil.getFieldValue(entity, "_id").toString());
            }
        }

        for (String duplicate : duplicates) {
            Map<String, Object> parameterDelete = new HashMap<>();
            parameterDelete.put("app_id", appId);
            parameterDelete.put("entry_id", entryId);
            parameterDelete.put("data_id", duplicate);
            String jsonDataDelete = JSONUtil.toJsonStr(parameterDelete);
            JSONObject jdyDataDelete = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/delete", headers, jsonDataDelete);
        }
    }
}
